import axios from 'axios'
import {
    Message,
    Loading
} from 'element-ui'
import store from './../store'
import {
    getToken
} from '@/utils/auth'
import router from '../router/index'
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 10000
})

let loadingInstance
let count = 0


service.interceptors.request.use(
    (config, next) => {
      // console.log(store.state,'aaaaaa')
        config.data = {
            data: config.data,
            header: {
                token: store.state.token || ''
                    // token: '63da6432cd64429aa109d42bf5b80e88'
            }
        }
		config.headers['token'] = store.state.token
        loadingInstance = Loading.service()
        count++
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        count--
        if (count === 0) {
            loadingInstance.close()
        }
        const res = response.data
		if(response.status==403){
			router.push('/login')
			Message.error({
			    message: "登录已获取，请重新登录"
			})
		}
        if (res.code !== 'AA000000') {
            if (res.code == 'AU000002' || res.code == 'AU000001') {
                router.push('/login')
                Message.error({
                    message: res.msg
                })
            }
            Message({
                message: res.data || res.msg || 'Error',
                type: 'error',
                duration: 5 * 1000
            })
            return Promise.reject(new Error(res.data || res.msg || 'Error'))
        } else {
            return res
        }
    },
    error => {
        count--
        if (count === 0) {
            loadingInstance.close()
        }
        Message({
            message: '服务器错误',
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
